<?php

/**
 * [PHPFOX_HEADER]
 */
defined('PHPFOX') or exit('NO DICE!');

/**
 * 
 * 
 * @copyright		[PHPFOX_COPYRIGHT]
 * @author  		Raymond Benc
 * @package 		Phpfox_Component
 * @version 		$Id: index.class.php 300 2009-03-20 13:01:54Z Raymond_Benc $
 */
class Loginsocial_Component_Controller_Login extends Phpfox_Component {

    /**
     * Class process method wnich is used to execute this component.
     */
    
    public function process() {
        if (($sProvider = $this->request()->get('provider'))) {
            $oService = Phpfox::getService('loginsocial.process');
            
            $oService->authenticate($sProvider);
            
            $sProvider = @ trim( strip_tags($sProvider));
            
            
            $oProfile = $oService->getProfile();
            
            $aUser = NULL;
            $aOauth = Phpfox::getService('loginsocial')->get('provider = "' . $sProvider . '" AND identifier = "'. $oProfile->identifier .'"');
            
            if(Phpfox::isUser()) {
                //add data oauth for current user.
                $oService->add(Phpfox::getUserBy('user_id'));
            } else {
                //check login
                if($aOauth) {
                    $aUser = Phpfox::getService('loginsocial')->getUser('u.user_id = ' . $aOauth['user_id']);
                }
                
                //add oauth or add user
                if(!$aOauth || !$aUser) {
                    if($oProfile->emailVerified) {
                        $aUser = Phpfox::getService('loginsocial')->getUser('u.email = "' . Phpfox::getLib('database')->escape($oProfile->emailVerified) . '"');
                    }
                    
                    if(($aUser = $this->_processUser($aUser, $aOauth, $oProfile)) === FALSE) {
                        return FALSE;
                    }            
                }
                
                //sign in
                list($bIsLoggedIn, $aPostUserInfo) = Phpfox::getService('user.auth')->login($aUser['user_name'], null, false, 'user_name', true);
                
            }
        }
        //redirect to home page.
        $this->url()->send('');
    }
    
    private function _processUser($aUser, $aOauth, $oProfile) {
        $bIsAddNewUser = FALSE;
        if(!$aUser) {
            $bIsAddNewUser = TRUE;    
            $aUser = $this->_initDataUser($oProfile);
        }
        
        if(!$oProfile->emailVerified) {
            $bIsValidForm = FALSE;
            
            if(($aVals = $this->request()->getArray('val'))) {
                if($aVals['email']) {
                    $bIsValidForm = TRUE;
                    $aUser['email'] = $aVals['email'];
                }
                
                if(!$bIsValidForm) {
                    Phpfox::getComponent('loginsocial.email', array('bNoTemplate' => true), 'controller');
                    return FALSE;
                }
            }
        }
        
        //add New User
        if($bIsAddNewUser) {
            $iUserId = Phpfox::getService('user.process')->add($aUser);
            
            if($oProfile->photoURL) {
                $sImage = $this->_updateImageUser($oProfile->photoURL, $iUserId);
            }
            
            $aUser = Phpfox::getService('loginsocial')->getUser('u.user_id = ' . $iUserId);
        }
        
        //add Oauth
        if($aOauth) {
            Phpfox::getService('loginsocial.process')->update(array('user_id' => $iUserId), 'provider = "' . $aOauth['provider'] . '" AND identifier = "'. $aOauth['identifier'] .'"');
        } else {
            Phpfox::getService('loginsocial.process')->add($aUser['user_id']);
        }
        
        return $aUser;
    }
    
    private function _updateImageUser($sImageLink, $iUserId) {
        $sNewImage = md5($iUserId . PHPFOX_TIME . uniqid()) . '%s.jpg';

        Phpfox::getLib('file')->writeToCache($sNewImage, file_get_contents($sImageLink));
        copy(PHPFOX_DIR_CACHE . $sNewImage, Phpfox::getParam('core.dir_user') . sprintf($sNewImage, ''));

        unlink(PHPFOX_DIR_CACHE . $sNewImage);
        foreach (Phpfox::getParam('user.user_pic_sizes') as $iSize) {
            Phpfox::getLib('image')->createThumbnail(Phpfox::getParam('core.dir_user') . sprintf($sNewImage, ''), Phpfox::getParam('core.dir_user') . sprintf($sNewImage, '_' . $iSize), $iSize, $iSize);
            Phpfox::getLib('image')->createThumbnail(Phpfox::getParam('core.dir_user') . sprintf($sNewImage, ''), Phpfox::getParam('core.dir_user') . sprintf($sNewImage, '_' . $iSize . '_square'), $iSize, $iSize, false);
        }
        
        Phpfox::getLib('database')->update(Phpfox::getT('user'), array('user_image' => $sNewImage, 'server_id' => 0), 'user_id = ' . (int) $iUserId);
        
    }
    
    private function _initDataUser($oProfile) {
        $aVals = array();

        $aVals['year'] = $oProfile->birthYear;
        $aVals['day'] = $oProfile->birthDay;
        $aVals['month'] = $oProfile->birthMonth;

        $aVals['email'] = $oProfile->emailVerified;
        $aVals['full_name'] = @trim($oProfile->firstName . ' ' . $oProfile->lastName);
        $aVals['gender'] = $oProfile->gender == 'male' ? 1 : 2;
        return $aVals;
    }
    
    
    /**
     * Garbage collector. Is executed after this class has completed
     * its job and the template has also been displayed.
     */
    public function clean() {
        
    }

}

?>